package repository

import (
	"errors"
	"fmt"
	"go-base/db"
	"go-base/internal/models"
	"gorm.io/gorm"
)

func AddOrUpdateUser(phone string, additionalOnlineTime uint64) error {
	var user models.User
	result := db.Context.First(&user, "phone = ?", phone)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			// 如果没有记录，则创建新记录
			user = models.User{
				Phone:           phone,
				TotalOnlineTime: additionalOnlineTime,
			}
			if err := db.Context.Create(&user).Error; err != nil {
				return fmt.Errorf("创建用户失败: %v", err)
			}
		} else {
			return fmt.Errorf("查询用户失败: %v", result.Error)
		}
	} else {
		// 如果有记录，则更新记录
		user.TotalOnlineTime += additionalOnlineTime
		if err := db.Context.Save(&user).Error; err != nil {
			return fmt.Errorf("更新用户失败: %v", err)
		}
	}
	return nil
}

func DeleteUser(phone string) error {
	if err := db.Context.Delete(&models.User{}, "phone = ?", phone).Error; err != nil {
		return fmt.Errorf("删除用户失败: %v", err)
	}
	return nil
}

func GetUser(phone string) (*models.User, error) {
	var user models.User
	if err := db.Context.Where("phone = ?", phone).First(&user).Error; err != nil {
		return nil, fmt.Errorf("查询用户失败: %v", err)
	}
	return &user, nil
}

func ListUsers() ([]models.User, error) {
	var users []models.User
	if err := db.Context.Find(&users).Error; err != nil {
		return nil, fmt.Errorf("查询用户列表失败: %v", err)
	}
	return users, nil
}
